﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using SPC.Classes;
using System.Collections;
using SPC.Properties;
using System.Security.Policy;
using System.Security.Cryptography;
using SCPutils;
using System.Threading;

namespace SPC
{
    public partial class MainForm : Form
    {
        private PrintPenalty dataGridPrinter1 = null;
        private settingsForm objSettingsFrom = null;

        public MainForm()
        {
            InitializeComponent();

            ErrorMessage.debugMode = Properties.Settings.Default.debugMode;

            L_CB_PersonSelector.Text = Resources.L_CB_PersonSelector;
            L_CB_VersionSelector.Text = Resources.L_CB_VersionSelector;
            this.Text = Resources.TXT_MAIN_FORM_TITLE;
            GB_Persons.Text = Resources.GB_Persons;
            L_Person_Name.Text = Resources.L_Person_Name;
            L_Person_Address.Text = Resources.L_Person_Address;
            L_Person_ID.Text = Resources.L_Person_ID;
            B_Person_Save.Text = Resources.B_Person_Save;
            B_Person_Insert.Text = Resources.B_Person_Insert;
            B_Person_Delete.Text = Resources.B_Person_Delete;
            L_Person_ID_Value.Text = Resources.L_Person_ID_Value;
            GB_Penalty.Text = Resources.GB_Penalty;
            L_Penalty_Date.Text = Resources.L_Penalty_Date;
            L_Penalty_Rate.Text = Resources.L_Penalty_Rate;
            B_Penalty_Insert.Text = Resources.B_Penalty_Insert;
            B_Penalty_Delete.Text = Resources.B_Penalty_Delete;
            B_Penalty_Update.Text = Resources.B_Penalty_Update;
            B_Penalty_Publish.Text = Resources.B_Penalty_Publish;
            B_Penalty_Recalculate.Text = Resources.B_Penalty_Recalculate;
            L_Penalty_Total.Text = Resources.L_Penalty_Total;
            B_Print_Penalties.Text = Resources.B_Print_Penalties;
            //B_Print_Penalty_Preview.Text = Resources.B_Print_Penalty_Preview;
            B_Print_Penalty_Preview.Text = " ";
            L_Penalty_Rate_Total.Text = Resources.L_Penalty_Rate_Total;
            L_Penlaty_Penalty_Total.Text = Resources.L_Penlaty_Penalty_Total;
            B_Print_Summons.Text = Resources.B_Print_Summons;
            //B_Print_Summons_Preview.Text = Resources.B_Print_Summons_Preview;
            B_Print_Summons_Preview.Text = " ";

            L_ENTER_KEY_ACTION.Text = Properties.Resources.L_ENTER_KEY_ACTION_INSERT;
        }

        void SetupGridPrinter()
        {
            DataGrid dg = new DataGrid();
            dg.DataSource = DGV_Penalties.DataSource;
            DataTable dt = new DataTable();
            if (DGV_Penalties.Columns.Contains("ID")) DGV_Penalties.Columns.Remove("ID");
            dt = Utils.Data.GetDataTableFromDGV(DGV_Penalties);
            dataGridPrinter1 = new PrintPenalty(dg, printDocumentPenalty, dt);
        }

        private void ReloadPersonsDGV()
        {
            PersonEvents persEvent = new PersonEvents();
            DGV_Persons.DataSource = persEvent.GetAllPersons2GridView();
            DGV_Persons.Columns[0].HeaderText = "ID";
            DGV_Persons.Columns[0].Width = 0;

            DGV_Persons.Columns[1].HeaderText = Resources.TXT_PERSON_NAME;
            DGV_Persons.Columns[1].Width = 200;

            DGV_Persons.Columns[2].HeaderText = Resources.TXT_PERSON_ADDRESS;
            DGV_Persons.Columns[2].Width = 350;

        }
        private void ReloadPersonSelectorCB()
        {
            CB_PersonSelector.Items.Clear();

            PersonEvents persEvent = new PersonEvents();
            List<Person> listPersons = persEvent.GetAllPersons();

            foreach (Person objPers in listPersons)
            {
                CB_PersonSelector.Items.Add(new Utils.ComboItem(objPers.getName() + " - " + objPers.getAddress(), objPers.getID()));
            }

            CB_VersionSelector.Items.Clear();

            if (CB_PersonSelector.Items.Count > 0) CB_PersonSelector.SelectedIndex = 0;
        }

        private void ReloadPenaltyVesionsSelectorCB(List<Penalty> listPersonsPenalties)
        {
            CB_VersionSelector.Items.Clear();
            foreach (Penalty objPenalty in listPersonsPenalties)
            {
                bool boolIsDuplicated = false;
                foreach(Utils.ComboItem comboItem in CB_VersionSelector.Items)
                {
                    if(comboItem.getName() == objPenalty.getMonthYearVersion()) 
                    {
                        boolIsDuplicated = true;
                        break;
                    }
                }
                if (!boolIsDuplicated) CB_VersionSelector.Items.Add(new Utils.ComboItem(objPenalty.getMonthYearVersion(), objPenalty.getVersion()));
                TB_Penalty_Date.Focus();
            }
            if (CB_VersionSelector.Items.Count > 0) CB_VersionSelector.SelectedIndex = 0;
        }

        private void ReloadPenaltiesIfPersAndVersionSelected()
        {
            TB_Penalty_Date.Text = "";
            NUM_Penalty_Rate.Value = 0;

            B_Penalty_Delete.Visible = false;
            B_Penalty_Update.Visible = false;

            L_ENTER_KEY_ACTION.Text = Properties.Resources.L_ENTER_KEY_ACTION_INSERT;

            int intPenaltyVersion = 0;
            int intPersonID = ((Utils.ComboItem)CB_PersonSelector.SelectedItem).getKey();
            if (CB_VersionSelector.SelectedIndex >= 0)
                intPenaltyVersion = ((Utils.ComboItem)CB_VersionSelector.SelectedItem).getKey();
            
            PenaltyEvents penalEvents = new PenaltyEvents();
            penalEvents.GetAllPenalties4Person2GridView(intPersonID, intPenaltyVersion, DGV_Penalties, new List<Label> { L_Penalty_Total_Value, L_Penalty_Rate_Total_Value, L_Penlaty_Penalty_Total_Value, L_Penalties_Details, L_Penalties_Details2});
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            string serialNo = Utils.Security.getIdentifier("Win32_DiskDrive", "Model").ToString();
            if (Utils.Security._encode(serialNo) != Properties.Settings.Default.SPC_SERIAL_KEY)
            {
                MessageBox.Show(String.Format( Resources.TXT_SECURITY_LICENSE_REFUSE, serialNo, Properties.Settings.Default.SPC_SERIAL_KEY));
                Application.Exit();
            }
            //TB_Person_Name.Text = Utils.Security._encode(serialNo);

            ReloadPersonsDGV();
            ReloadPersonSelectorCB();
        }

        private void DGV_Persons_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex.ToString() != "-1")
            {
                String strPersonID = DGV_Persons.Rows[e.RowIndex].Cells[0].Value.ToString();

                //MessageBox.Show(strPersonID);

                PersonEvents persEvent = new PersonEvents();
                Person person = persEvent.GetAllPerson(int.Parse(strPersonID));

                TB_Person_Name.Text = person.getName();
                TB_Person_Address.Text = person.getAddress();
                L_Person_ID.Text = Resources.L_Person_ID + " : ";
                L_Person_ID_Value.Text = person.getID();
            }
        }

        private void B_Person_Save_Click(object sender, EventArgs e)
        {
            Person objUpdatePerosn = new Person();
            objUpdatePerosn.setID(L_Person_ID_Value.Text);
            objUpdatePerosn.setName(TB_Person_Name.Text);
            objUpdatePerosn.setAddress(TB_Person_Address.Text);

            PersonEvents eventPersons = new PersonEvents();
            eventPersons.Update(objUpdatePerosn);

            //Refresh Table.
            ReloadPersonsDGV();
            ReloadPersonSelectorCB();
        }

        private void B_Person_Insert_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show(Resources.TXT_INSERT_CONFIRMATION, Resources.TXT_CONFIRMATION_TITLE, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                Person objUpdatePerosn = new Person();
                objUpdatePerosn.setID(null);
                objUpdatePerosn.setName(TB_Person_Name.Text);
                objUpdatePerosn.setAddress(TB_Person_Address.Text);

                PersonEvents eventPersons = new PersonEvents();
                eventPersons.Insert(objUpdatePerosn);

                L_Person_ID_Value.Text = "-";

                //Refresh Table.
                ReloadPersonsDGV();
                ReloadPersonSelectorCB();
            }
        }

        private void B_Person_Delete_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show(String.Format(Resources.TXT_DELETE_CONFIRMATION, TB_Person_Name.Text), Resources.TXT_CONFIRMATION_TITLE, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                PersonEvents eventPersons = new PersonEvents();
                eventPersons.Delete(L_Person_ID_Value.Text);

                L_Person_ID_Value.Text = "-";

                //Refresh Table.
                ReloadPersonsDGV();
                ReloadPersonSelectorCB();
            }
        }

        private void CB_PersonSelector_SelectedIndexChanged(object sender, EventArgs e)
        {
            CB_VersionSelector.Items.Clear();
            DGV_Penalties.Rows.Clear();
            int intPersonID = ((Utils.ComboItem)CB_PersonSelector.SelectedItem).getKey();
            List<Penalty> listPersonsPenalties = new List<Penalty>();
            PenaltyEvents penalEvents = new PenaltyEvents();
            listPersonsPenalties = penalEvents.GetAllPenalties4Person(intPersonID);
            if (listPersonsPenalties.Count > 0) ReloadPenaltyVesionsSelectorCB(listPersonsPenalties);
            L_Penalty_ID_Value.Text = "-";

        }

        private void CB_VersionSelector_SelectedIndexChanged(object sender, EventArgs e)
        {

            if (CB_VersionSelector.Items.Count > 0)
            {
                if (((Utils.ComboItem)CB_VersionSelector.SelectedItem).getName() != Utils.Unix.GetMonthYearFormatFromCurrentMonth())
                {
                    B_Penalty_Delete.Enabled = false;
                    B_Penalty_Update.Enabled = false;
                    B_Penalty_Insert.Enabled = false;
                    L_ENTER_KEY_ACTION.Visible = false;
                    MessageBox.Show(Properties.Resources.TXT_OLD_VERSIONS_WARNING, Properties.Resources.TXT_WARNING_TITLE, MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                {
                    B_Penalty_Delete.Enabled = true;
                    B_Penalty_Update.Enabled = true;
                    B_Penalty_Insert.Enabled = true;
                    L_ENTER_KEY_ACTION.Visible = true;
                }
            }

            ReloadPenaltiesIfPersAndVersionSelected();
        }

        private void NUM_Penalty_Rate_Enter(object sender, EventArgs e)
        {
            NUM_Penalty_Rate.BackColor = Color.Moccasin;

            NUM_Penalty_Rate.Select(0, NUM_Penalty_Rate.ToString().Length);
            if (TB_Penalty_Date.Text.Length < 7) TB_Penalty_Date.Focus();
        }

        private void TB_Penalty_Date_Enter(object sender, EventArgs e)
        {
            TB_Penalty_Date.BackColor = Color.Moccasin;
            TB_Penalty_Date.SelectAll();
        }

        private void DGV_Persons_SelectionChanged(object sender, EventArgs e)
        {
            if (DGV_Persons.SelectedRows.Count > 0)
            {
                String strPersonID = DGV_Persons.SelectedRows[0].Cells[0].Value.ToString();

                //MessageBox.Show(strPersonID);

                PersonEvents persEvent = new PersonEvents();
                Person person = persEvent.GetAllPerson(int.Parse(strPersonID));

                TB_Person_Name.Text = person.getName();
                TB_Person_Address.Text = person.getAddress();
                L_Person_ID.Text = Resources.L_Person_ID + " : ";
                L_Person_ID_Value.Text = person.getID();
            }
        }

        private void B_Penalty_Insert_Click(object sender, EventArgs e)
        {
            L_Penalty_ID_Value.Text = "-";

            if (Utils.Unix.GetUnixTimestampSecondsFromMonthYear(TB_Penalty_Date.Text) < 0)
            {
                MessageBox.Show(String.Format(Resources.TXT_WARNING_NO_DATE, TB_Penalty_Date.Text), Resources.TXT_WARNING_TITLE, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            //MessageBox.Show(CB_PersonSelector.SelectedIndex.ToString());
            //MessageBox.Show(CB_VersionSelector.SelectedIndex.ToString());
            bool boolMonthAlreadyInside = false;
            foreach(DataGridViewRow DGV_Row in DGV_Penalties.Rows)
            {
                if ((string)DGV_Row.Cells[1].Value == TB_Penalty_Date.Text)
                {
                    boolMonthAlreadyInside = true;
                    MessageBox.Show(String.Format(Resources.TXT_PENALTY_DATE_EXIST, TB_Penalty_Date.Text), Resources.TXT_WARNING_TITLE, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    break;
                }
            }

            if (CB_PersonSelector.SelectedIndex >= 0 && !boolMonthAlreadyInside) //&& CB_VersionSelector.SelectedIndex >= 0
            {
                int intPersonID = ((Utils.ComboItem)CB_PersonSelector.SelectedItem).getKey();

                bool boolNewVersion4NewPerson = false;
                int intPenaltyVersion;
                if (CB_VersionSelector.SelectedIndex >= 0)
                    intPenaltyVersion = ((Utils.ComboItem)CB_VersionSelector.SelectedItem).getKey();
                else
                {
                    intPenaltyVersion = (int)Utils.Unix.GetUnixTimestampSecondsFromCurrentMonth();
                    boolNewVersion4NewPerson = true;
                }

                String strDateMonthYear = TB_Penalty_Date.Text;
                double decPenaltyRate = (double)NUM_Penalty_Rate.Value;

                Penalty objPenalty2Insert = new Penalty();
                objPenalty2Insert.setPersonID(intPersonID.ToString());
                objPenalty2Insert.setVersion(intPenaltyVersion.ToString());

                objPenalty2Insert.setDate_FromMonthYear(strDateMonthYear);
                objPenalty2Insert.setRate(decPenaltyRate.ToString());

                objPenalty2Insert.calculatePenalty();

                PenaltyEvents eventPenalty = new PenaltyEvents();
                eventPenalty.Insert(objPenalty2Insert);

                if (boolNewVersion4NewPerson)
                {
                    int storeOldSelectedPerson = CB_PersonSelector.SelectedIndex;
                    ReloadPersonSelectorCB();
                    CB_PersonSelector.SelectedIndex = storeOldSelectedPerson;
                }
                    //Refresh Penalties
                ReloadPenaltiesIfPersAndVersionSelected();


                NUM_Penalty_Rate.Value = 0;
                TB_Penalty_Date.Text = "";
                TB_Penalty_Date.Focus();
            }
            else
            {
                if(CB_PersonSelector.SelectedIndex == -1)
                    MessageBox.Show(Resources.TXT_PENALTY_INSERT_WARNING, Resources.TXT_WARNING_TITLE, MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        private void B_Penalty_Delete_Click(object sender, EventArgs e)
        {
            if (L_Penalty_ID_Value.Text != "-")
            {
                if (MessageBox.Show(Resources.TXT_DELETE_PENALTY_CONFIRMATION, Resources.TXT_CONFIRMATION_TITLE, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    PenaltyEvents eventPenalty = new PenaltyEvents();
                    eventPenalty.Delete(L_Penalty_ID_Value.Text);

                    L_Penalty_ID_Value.Text = "-";

                    //Refresh Table.
                    ReloadPenaltiesIfPersAndVersionSelected();
                }
            }
            else
            {
                MessageBox.Show(Resources.TXT_PENALTY_DELETE_WARNING_INVALID_ID, Resources.TXT_WARNING_TITLE, MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        private void DGV_Penalties_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex.ToString() != "-1" && B_Penalty_Insert.Enabled)
            {
                String strPenaltyID = DGV_Penalties.Rows[e.RowIndex].Cells[0].Value.ToString();
                
                L_Penalty_ID_Value.Text = strPenaltyID;

                PenaltyEvents penaltyEvent = new PenaltyEvents();
                Penalty penalty = penaltyEvent.GetPenalty(strPenaltyID);

                TB_Penalty_Date.Text = penalty.getDate_MonthYearFormat();
                NUM_Penalty_Rate.Value = decimal.Parse(penalty.getRate());

                B_Penalty_Update.Visible = true;
                B_Penalty_Delete.Visible = true;
                L_ENTER_KEY_ACTION.Text = Properties.Resources.L_ENTER_KEY_ACTION_UPDATE;
            }
        }

        private void B_Penalty_Publish_Click(object sender, EventArgs e)
        {
            
        }

        private void B_Penalty_Recalculate_Click(object sender, EventArgs e)
        {
            PB_Spinner.Visible = true;

            if (MessageBox.Show(Properties.Resources.TXT_RECALCULATE_WARNING, Properties.Resources.TXT_RECALCULATE_TITLE, MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1) == DialogResult.Yes)
            {
                this.Cursor = Cursors.WaitCursor;

                if (CB_PersonSelector.SelectedIndex >= 0 && CB_VersionSelector.SelectedIndex >= 0)
                {
                    int intPersonID = ((Utils.ComboItem)CB_PersonSelector.SelectedItem).getKey();
                    int intPenaltyVersion = ((Utils.ComboItem)CB_VersionSelector.SelectedItem).getKey();

                    bool boolRecalculateInNewMonth = false;
                    bool boolCancelRecalculate = false;
                    if (((Utils.ComboItem)CB_VersionSelector.SelectedItem).getName() != Utils.Unix.GetMonthYearFormatFromCurrentMonth())
                    {
                        if (((Utils.ComboItem)CB_VersionSelector.Items[0]).getName() == Utils.Unix.GetMonthYearFormatFromCurrentMonth())
                        {
                            MessageBox.Show(Properties.Resources.TXT_RECALCULATE_IMPOSIBLE, Properties.Resources.TXT_WARNING_TITLE, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                            boolCancelRecalculate = true;
                        }
                        boolRecalculateInNewMonth = true;
                    }

                    if (!boolCancelRecalculate)
                    {
                        List<Penalty> listPenalty = new List<Penalty>();
                        PenaltyEvents pE = new PenaltyEvents();
                        listPenalty = pE.GetAllPenalties4Person(intPersonID, intPenaltyVersion);

                        foreach (Penalty objPenalty in listPenalty)
                        {
                            //recalculate each row and update DB
                            objPenalty.calculatePenalty();
                            if (!boolRecalculateInNewMonth)
                            {
                                pE.Update(objPenalty);
                            }
                            else
                            {
                                objPenalty.setID("");
                                objPenalty.setVersion(Utils.Unix.GetUnixTimestampSecondsFromCurrentMonth().ToString());
                                pE.Insert(objPenalty);
                            }
                        }

                        ReloadPenaltiesIfPersAndVersionSelected();
                    }
                }
                else
                {
                    MessageBox.Show(Properties.Resources.TXT_RECALCULATE_NO_PERS_NO_VERSION, Properties.Resources.TXT_WARNING_TITLE, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }

                this.Cursor = Cursors.Arrow;
            }
            PB_Spinner.Visible = false;
        }

        private void B_Print_Penalties_Click(object sender, EventArgs e)
        {
            SetupGridPrinter();

            dataGridPrinter1.PageNumber = 1;
            dataGridPrinter1.RowCount = 0;
            if (printDialog1.ShowDialog() == DialogResult.OK)
            {
                printDocumentPenalty.Print();
            }

            ReloadPenaltiesIfPersAndVersionSelected();

        }

        private void printDocumentPenalty_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
        {
            Graphics g = e.Graphics;
            DrawTopLabel(g);
            bool more = dataGridPrinter1.DrawDataGrid(g);
            if (more == true)
            {
                e.HasMorePages = true;
                dataGridPrinter1.PageNumber++;
            }
            DrawTotalLabel(g);
        }

        void DrawTopLabel(Graphics g)
        {
            Int32 lines;
        	Int32 chars;
            //Use the StringFormat class for the text layout of our document
    	    StringFormat format = new StringFormat(StringFormatFlags.LineLimit);

            int TopMargin = printDocumentPenalty.DefaultPageSettings.Margins.Top;

            int printHeight = dataGridPrinter1.DefaultPageSettings.PaperSize.Height - dataGridPrinter1.DefaultPageSettings.Margins.Top - dataGridPrinter1.DefaultPageSettings.Margins.Bottom;
            int printWidth = dataGridPrinter1.DefaultPageSettings.PaperSize.Width - dataGridPrinter1.DefaultPageSettings.Margins.Left - dataGridPrinter1.DefaultPageSettings.Margins.Right;

            int leftMargin = dataGridPrinter1.DefaultPageSettings.Margins.Left;  //X
            int rightMargin = dataGridPrinter1.DefaultPageSettings.Margins.Top;  //Y

            RectangleF printArea = new RectangleF(leftMargin, rightMargin, printWidth, printHeight);
            
            //g.FillRectangle(new SolidBrush(Color.White), 200, 50 + TopMargin, 100, 50);

            printArea.X += 120;
            g.MeasureString(Properties.Settings.Default.PRINT_PENALTY_TITLE, new Font("Arial", 14), new SizeF(printWidth, printHeight), format, out chars, out lines);
            g.DrawString(Properties.Settings.Default.PRINT_PENALTY_TITLE, new Font("Arial", 14), new SolidBrush(Color.Black), printArea, format);
            printArea.X -= 120;

            printArea.Y += 30;

            printArea.X += 150;
            g.MeasureString(Properties.Settings.Default.PRINT_DOMAIN, new Font("Arial", 12), new SizeF(printWidth, printHeight), format, out chars, out lines);
            g.DrawString(Properties.Settings.Default.PRINT_DOMAIN, new Font("Arial", 12), new SolidBrush(Color.Black), printArea, format);
            printArea.X -= 150;

            printArea.Y += 60;

            g.MeasureString(((Utils.ComboItem)(CB_PersonSelector.SelectedItem)).getName(), new Font("Arial", 12), new SizeF(printWidth, printHeight), format, out chars, out lines);
            g.DrawString(((Utils.ComboItem)(CB_PersonSelector.SelectedItem)).getName(), new Font("Arial", 12), new SolidBrush(Color.Black), printArea, format);

            //g.DrawString(Settings.Default.PRINT_PENALTY_TITLE, new Font("Arial", 14), new SolidBrush(Color.Black), 170 + 50, 20 + TopMargin, new StringFormat());
            //g.DrawString(Settings.Default.PRINT_DOMAIN, new Font("Arial", 12), new SolidBrush(Color.Black), 100 + 50, 50 + TopMargin, new StringFormat());
            //g.DrawString(((Utils.ComboItem)(CB_PersonSelector.SelectedItem)).getName(), new Font("Arial", 12), new SolidBrush(Color.Black), 30 + 50, 80 + TopMargin, new StringFormat());

        }

        void DrawTotalLabel(Graphics g)
        {
            Int32 lines;
            Int32 chars;
            //Use the StringFormat class for the text layout of our document
            StringFormat format = new StringFormat(StringFormatFlags.LineLimit);

            int TopMargin = printDocumentPenalty.DefaultPageSettings.Margins.Top;

            int printHeight = dataGridPrinter1.DefaultPageSettings.PaperSize.Height - dataGridPrinter1.DefaultPageSettings.Margins.Top - dataGridPrinter1.DefaultPageSettings.Margins.Bottom;
            int printWidth = dataGridPrinter1.DefaultPageSettings.PaperSize.Width - dataGridPrinter1.DefaultPageSettings.Margins.Left - dataGridPrinter1.DefaultPageSettings.Margins.Right;

            int leftMargin = dataGridPrinter1.DefaultPageSettings.Margins.Left;  //X
            int rightMargin = dataGridPrinter1.DefaultPageSettings.Margins.Top;  //Y

            RectangleF printArea = new RectangleF(75, printHeight+50, printWidth, printHeight);

            g.MeasureString(L_Penalty_Rate_Total.Text + L_Penalty_Rate_Total_Value.Text + "                      " + L_Penlaty_Penalty_Total.Text + L_Penlaty_Penalty_Total_Value.Text, new Font("Arial", 10), new SizeF(printWidth, printHeight), format, out chars, out lines);
            g.DrawString(L_Penalty_Rate_Total.Text + L_Penalty_Rate_Total_Value.Text + "                      " + L_Penlaty_Penalty_Total.Text + L_Penlaty_Penalty_Total_Value.Text, new Font("Arial", 10), new SolidBrush(Color.Black), printArea, format);

            printArea.X += 500;
            g.MeasureString(L_Penalty_Total.Text + L_Penalty_Total_Value.Text, new Font("Arial", 14), new SizeF(printWidth, printHeight), format, out chars, out lines);
            g.DrawString(L_Penalty_Total.Text + L_Penalty_Total_Value.Text, new Font("Arial", 14), new SolidBrush(Color.Black), printArea, format);
            printArea.X -= 500;

            printArea.Y += 50;
            printArea.X += 300;
            g.MeasureString("-" + DateTime.Now.ToString("dd.MM.yyyy") + "-", new Font("Arial", 10), new SizeF(printWidth, printHeight), format, out chars, out lines);
            g.DrawString("-" + DateTime.Now.ToString("dd.MM.yyyy") + "-", new Font("Arial", 10), new SolidBrush(Color.Black), printArea, format);
        }

        private void B_Print_Penalty_Preview_Click(object sender, EventArgs e)
        {
            SetupGridPrinter();

            dataGridPrinter1.PageNumber = 1;
            dataGridPrinter1.RowCount = 0;
            if (this.printPreviewDialog1.ShowDialog() == DialogResult.OK)
            {
            }

            ReloadPenaltiesIfPersAndVersionSelected();

        }

        private void printPreviewDialog1_Load(object sender, EventArgs e)
        {
            printPreviewDialog1.Bounds = ClientRectangle;
        }

        private void TB_Penalty_Date_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                if (TB_Penalty_Date.Text.Length > 1) NUM_Penalty_Rate.Focus();
            }
        }

        private void NUM_Penalty_Rate_KeyUp(object sender, KeyEventArgs e)
        {
            //if (e.KeyCode == Keys.Enter)
            //{
            //    //MessageBox.Show(NUM_Penalty_Rate.Value.ToString());
            //    if (MessageBox.Show(Resources.TXT_KEYBOARD_INSERT_PENALTY, Resources.TXT_WARNING_TITLE, MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1) == DialogResult.OK)
            //    {
            //        B_Penalty_Insert_Click(null, new EventArgs());
            //        TB_Penalty_Date.Text = "";
            //    }
            //    TB_Penalty_Date.Focus();
            //}
        }

        private void B_VersionShow_Click(object sender, EventArgs e)
        {
            AboutSPC aboutSPC = new AboutSPC();
            aboutSPC.ShowDialog();
        }

        private void B_Print_Summons_Click(object sender, EventArgs e)
        {
            SetupGridPrinter();

            dataGridPrinter1.PageNumber = 1;
            dataGridPrinter1.RowCount = 0;
            if (printDialog1.ShowDialog() == DialogResult.OK)
            {
                printDocumentSummon.Print();
            }

            ReloadPenaltiesIfPersAndVersionSelected();
        }

        private void B_Print_Summons_Preview_Click(object sender, EventArgs e)
        {
            SetupGridPrinter();

            dataGridPrinter1.PageNumber = 1;
            dataGridPrinter1.RowCount = 0;
            if (this.printPreviewDialog2.ShowDialog() == DialogResult.OK)
            {
            }

            //ReloadPenaltiesIfPersAndVersionSelected();
        }

        private void printPreviewDialog2_Load(object sender, EventArgs e)
        {
            printPreviewDialog2.Bounds = ClientRectangle;
        }

        private void printDocumentSummon_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
        {
            Graphics g = e.Graphics;
            DrawSummon(g);
            //bool more = dataGridPrinter1.DrawSummon(g);
            //DrawTotalLabel(g);
        }

        void DrawSummon(Graphics g)
        {
            Int32 lines;
            Int32 chars;
            //Use the StringFormat class for the text layout of our document
            StringFormat format = new StringFormat(StringFormatFlags.LineLimit);

            int TopMargin = printDocumentSummon.DefaultPageSettings.Margins.Top;

            int printHeight = dataGridPrinter1.DefaultPageSettings.PaperSize.Height - dataGridPrinter1.DefaultPageSettings.Margins.Top - dataGridPrinter1.DefaultPageSettings.Margins.Bottom;
            int printWidth = dataGridPrinter1.DefaultPageSettings.PaperSize.Width - dataGridPrinter1.DefaultPageSettings.Margins.Left - dataGridPrinter1.DefaultPageSettings.Margins.Right;

            int leftMargin = dataGridPrinter1.DefaultPageSettings.Margins.Left;  //X
            int rightMargin = dataGridPrinter1.DefaultPageSettings.Margins.Top;  //Y

            int intPrintLocationLowerValue = 0;
            if (RB_Print_Summon_1st.Checked) intPrintLocationLowerValue = 0;
            if (RB_Print_Summon_2nd.Checked) intPrintLocationLowerValue = 300;
            if (RB_Print_Summon_3rd.Checked) intPrintLocationLowerValue = 600;

            //for each position... add X
            RectangleF printArea = new RectangleF(leftMargin, rightMargin + intPrintLocationLowerValue, printWidth, printHeight);

            g.MeasureString(Properties.Settings.Default.PRINT_DOMAIN, new Font("Arial", 10), new SizeF(printWidth, printHeight), format, out chars, out lines);
            g.DrawString(Properties.Settings.Default.PRINT_DOMAIN, new Font("Arial", 10), new SolidBrush(Color.Black), printArea, format);

            printArea.Y += 30;

            printArea.X += 300;
            g.MeasureString(Properties.Settings.Default.PRINT_SUMMON_HEADER, new Font("Arial", 9), new SizeF(printWidth, printHeight), format, out chars, out lines);
            g.DrawString(Properties.Settings.Default.PRINT_SUMMON_HEADER, new Font("Arial", 9), new SolidBrush(Color.Black), printArea, format);
            printArea.X -= 300;

            printArea.Y += 50;

            printArea.X += 200;
            g.MeasureString(Properties.Settings.Default.PRINT_SUMMON_TITLE, new Font("Arial", 14), new SizeF(printWidth, printHeight), format, out chars, out lines);
            g.DrawString(Properties.Settings.Default.PRINT_SUMMON_TITLE, new Font("Arial", 14), new SolidBrush(Color.Black), printArea, format);
            printArea.X -= 200;


            printArea.Y += 50;

            g.MeasureString(Properties.Settings.Default.PRINT_SUMMON_TO +" "+ ((Utils.ComboItem)(CB_PersonSelector.SelectedItem)).getName(), new Font("Arial", 10), new SizeF(printWidth, printHeight), format, out chars, out lines);
            g.DrawString(Properties.Settings.Default.PRINT_SUMMON_TO + " " + ((Utils.ComboItem)(CB_PersonSelector.SelectedItem)).getName(), new Font("Arial", 10), new SolidBrush(Color.Black), printArea, format);

            printArea.Y += 30;

            g.MeasureString(String.Format(Properties.Settings.Default.PRINT_SUMMON_BODY, String.Format(Properties.Settings.Default.PRINT_SUMMON_BODY_TOTALS_DETAILS, L_Penalty_Rate_Total_Value.Text,L_Penlaty_Penalty_Total_Value.Text, L_Penalty_Total_Value.Text), Properties.Settings.Default.PENALTY_PERCENT_VALUE), new Font("Arial", 10), new SizeF(printWidth, printHeight), format, out chars, out lines);
            g.DrawString(String.Format(Properties.Settings.Default.PRINT_SUMMON_BODY, String.Format(Properties.Settings.Default.PRINT_SUMMON_BODY_TOTALS_DETAILS, L_Penalty_Rate_Total_Value.Text, L_Penlaty_Penalty_Total_Value.Text, L_Penalty_Total_Value.Text), Properties.Settings.Default.PENALTY_PERCENT_VALUE), new Font("Arial", 10), new SolidBrush(Color.Black), printArea, format);

            printArea.Y += 80;

            printArea.X += 400;
            g.MeasureString(Properties.Settings.Default.PRINT_SUMMON_ADMIN, new Font("Arial", 10), new SizeF(printWidth, printHeight), format, out chars, out lines);
            g.DrawString(Properties.Settings.Default.PRINT_SUMMON_ADMIN, new Font("Arial", 10), new SolidBrush(Color.Black), printArea, format);
            printArea.X -= 400;

            printArea.Y += 30;

            g.DrawLine(new Pen(Color.Black, 1), printArea.X, printArea.Y, printArea.X + printWidth, printArea.Y);
            
            //g.DrawString(Properties.Settings.Default.PRINT_PENALTY_TITLE, new Font("Arial", 14), new SolidBrush(Color.Black), 170 + 50, 20 + TopMargin, new StringFormat());
            //g.DrawString(Properties.Settings.Default.PRINT_DOMAIN, new Font("Arial", 12), new SolidBrush(Color.Black), 100 + 50, 50 + TopMargin, new StringFormat());
            //g.DrawString(((Utils.ComboItem)(CB_PersonSelector.SelectedItem)).getName(), new Font("Arial", 12), new SolidBrush(Color.Black), 30 + 50, 80 + TopMargin, new StringFormat());

        }

        private void NUM_Penalty_Rate_KeyDown(object sender, KeyEventArgs e)
        {
            //MessageBox.Show(e.KeyCode.ToString());
            if (e.KeyCode == Keys.OemPeriod || e.KeyCode == Keys.Decimal)
            {
                e.SuppressKeyPress = true;
                NUM_Penalty_Rate.Select(NUM_Penalty_Rate.Value.ToString().Length+1, NUM_Penalty_Rate.Value.ToString().Length+2);
            }

            if (e.KeyCode == Keys.Enter && B_Penalty_Insert.Enabled)
            {
                //MessageBox.Show(NUM_Penalty_Rate.Value.ToString());
                if (MessageBox.Show(B_Penalty_Update.Visible ? Resources.TXT_KEYBOARD_UPDATE_PENALTY : Resources.TXT_KEYBOARD_INSERT_PENALTY, Resources.TXT_WARNING_TITLE, MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1) == DialogResult.OK)
                {
                    if(L_Penalty_ID.Text == "-") B_Penalty_Insert_Click(null, new EventArgs());
                    else B_Penalty_Update_Click(null, new EventArgs());
                    TB_Penalty_Date.Text = "";
                }
                TB_Penalty_Date.Focus();
            }
        }

        private void TB_Person_Name_Enter(object sender, EventArgs e)
        {
            TB_Person_Name.BackColor = Color.Moccasin;
        }

        private void TB_Person_Name_Leave(object sender, EventArgs e)
        {
            TB_Person_Name.BackColor = SystemColors.Window;
        }

        private void TB_Person_Address_Enter(object sender, EventArgs e)
        {
            TB_Person_Address.BackColor = Color.Moccasin;
        }

        private void TB_Person_Address_Leave(object sender, EventArgs e)
        {
            TB_Person_Address.BackColor = SystemColors.Window;
        }

        private void TB_Penalty_Date_Leave(object sender, EventArgs e)
        {
            TB_Penalty_Date.BackColor = SystemColors.Window;

            if (TB_Penalty_Date.Text.Length == 7)
            {
                foreach (DataGridViewRow row in DGV_Penalties.Rows)
                {
                    if (row.Cells[Resources.TXT_PENALTY_DATE].Value.ToString() == TB_Penalty_Date.Text)
                    {
                        MessageBox.Show(Resources.TXT_WARNING_DOUBLE_PENALTY, Resources.TXT_WARNING_TITLE, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }
                }
            }
        }

        private void NUM_Penalty_Rate_Leave(object sender, EventArgs e)
        {
            NUM_Penalty_Rate.BackColor = SystemColors.Window;
        }

        private void TB_Penalty_Date_KeyDown(object sender, KeyEventArgs e)
        {
            //if (e.KeyCode == Keys.Enter || e.KeyCode == Keys.Tab)
            //{
                
            //}
        }

        private void B_Settings_Click(object sender, EventArgs e)
        {
            if (objSettingsFrom == null)
            {
                objSettingsFrom = new settingsForm();
                objSettingsFrom.StartPosition = FormStartPosition.CenterScreen;
                objSettingsFrom.FormClosed += new FormClosedEventHandler(objSettingsFrom_FormClosed);
                objSettingsFrom.ShowDialog();
            }
            else objSettingsFrom.Focus();
        }

        private void objSettingsFrom_FormClosed(object sender, FormClosedEventArgs e)
        {

            this.objSettingsFrom = null;
        }

        private void B_Penalty_Update_Click(object sender, EventArgs e)
        {
            if (L_Penalty_ID_Value.Text != "-")
            {
                if (Utils.Unix.GetUnixTimestampSecondsFromMonthYear(TB_Penalty_Date.Text) < 0)
                {
                    MessageBox.Show(String.Format(Resources.TXT_WARNING_NO_DATE, TB_Penalty_Date.Text), Resources.TXT_WARNING_TITLE, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                bool boolMonthAlreadyInside = false;
                foreach (DataGridViewRow DGV_Row in DGV_Penalties.Rows)
                {
                    if ((string)DGV_Row.Cells[1].Value == TB_Penalty_Date.Text && (string)DGV_Row.Cells[0].Value == L_Penalty_ID.Text)
                    {
                        boolMonthAlreadyInside = true;
                        MessageBox.Show(String.Format(Resources.TXT_PENALTY_DATE_EXIST, TB_Penalty_Date.Text), Resources.TXT_WARNING_TITLE, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        break;
                    }
                }

                if (!boolMonthAlreadyInside)
                {
                    PenaltyEvents eventPenalty = new PenaltyEvents();
                    Penalty objPenalty = eventPenalty.GetPenalty(L_Penalty_ID_Value.Text);
                    objPenalty.setDate_FromMonthYear(TB_Penalty_Date.Text);
                    objPenalty.setRate(NUM_Penalty_Rate.Value.ToString());

                    objPenalty.calculatePenalty();

                    eventPenalty.Update(objPenalty);

                    L_Penalty_ID_Value.Text = "-";

                    //Refresh Table.
                    ReloadPenaltiesIfPersAndVersionSelected();
                }
            }
            else
            {
                MessageBox.Show(Resources.TXT_PENALTY_DELETE_WARNING_INVALID_ID, Resources.TXT_WARNING_TITLE, MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
    }
}
